﻿using Microsoft.AspNetCore.SignalR;
using SignalR.Server.Controllers;
using System.Reflection;
using System.Threading.Channels;
using System.Xml.Linq;

namespace SignalR.Server.Hubs
{
    public class ChatHub : Hub
    {
        private readonly ILogger<ChatHub> _logger;

        public ChatHub(ILogger<ChatHub> logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 被客户端调用 （无返回值）
        /// </summary>
        /// <param name="msg"></param>
        public void CallByClient(string msg)
        {  
            _logger.LogInformation("被客户端调用===客户端发来消息", msg);
        }

        /// <summary>
        /// 被客户端调用 （有返回值）
        /// </summary>
        /// <param name="msg"></param>
        public string CallByClientWithReturn(string msg)
        {
            _logger.LogInformation("============被客户端调用（有返回值）============"); 
            return "CallByClientWithReturn=====" + MethodInfo.GetCurrentMethod()?.Name + "";
        }

        /// <summary>
        /// 调用客户端方法
        /// </summary>
        /// <param name="msg"></param>
        public string CallClient(string msg)
        {
            _logger.LogInformation("============调用客户端方法============");
            Clients.Caller.SendAsync("CallByHub", $"CallByClientWithReturn by {Context.ConnectionId}"); //谁调的 返回去调谁
            return "CallByClientWithReturn=====" + MethodInfo.GetCurrentMethod()?.Name + "";
        }
        /// <summary>
        /// 调用客户端方法 
        /// 全员发送
        /// </summary>
        /// <param name="msg"></param>
        public string CallAllClients(string msg)
        {
            _logger.LogInformation("============全员发送============");

            Clients.All.SendAsync("CallByHub", $"callAllClient by {Context.ConnectionId}");

            return MethodInfo.GetCurrentMethod()?.Name + "";
        }

        /// <summary>
        /// 调用客户端方法 
        /// 向自身以外发送
        /// </summary>
        /// <param name="msg"></param>
        public string CallOtherClients(string msg)
        {
            _logger.LogInformation("============向自身以外发送============");

            Clients.Others.SendAsync("CallByHub", $"callAllClient by {Context.ConnectionId}");

            return MethodInfo.GetCurrentMethod()?.Name + "";
        }

 
        //注册到分组
        public void RegisterToGroup(string grpName)
        {
            _logger.LogInformation($"============客户端传来数据=====RegisterToGroup===={grpName}===");
            Groups.AddToGroupAsync(Context.ConnectionId, grpName);
        }
        /// <summary>
        /// 分组发送
        /// </summary>
        /// <param name="name"></param>
        public void SendToGroup(string name)
        {
            _logger.LogInformation("============分组发送============");
            _logger.LogInformation($"============客户端传来数据========={name}===");
            Clients.Groups(name).SendAsync("CallByHub", $"callAllClient by {Context.ConnectionId}=====分组发送");
 
        }

        /// <summary> 
        /// 指定发送
        /// </summary>
        /// <param name="msg"></param>
        public void SendToClient(string connid)
        {
            _logger.LogInformation("============指定发送============");
            _logger.LogInformation($"============客户端传来数据========={connid}===");
            Clients.Client(connid).SendAsync("CallByHub", $"callAllClient by {Context.ConnectionId}=====指定发送");
 
        }


        /// <summary> 
        /// 推流到客户端
        /// </summary>
        /// <param name="msg"></param>
        public async Task<ChannelReader<string>> SendStream()
        {
            _logger.LogInformation("============推流到客户端============");

            var channel = Channel.CreateUnbounded<string>();
            await Task.Run(async () =>
            {
                var lst = File.ReadAllLines("UploadFiles/001.txt");
                foreach (var item in lst)
                {
                    _logger.LogInformation(item);
                    await channel.Writer.WriteAsync(item);
                    await Task.Delay(1000);
                }
            });
            _logger.LogInformation("===================================");

            return channel.Reader;
        }
        /// <summary>
        /// 接收客户端流
        /// </summary>
        /// <returns></returns>
        public async Task GetClientStream(ChannelReader<string> reader)
        {
            await Task.Run(async () =>
            {
                while (await reader.WaitToReadAsync())
                {
                    while (reader.TryRead(out string str))
                    {
                        _logger.LogInformation("GetClientStream=====" + str);
                        await Task.Delay(1000);
                    }
                }
            });
        } 

    }
}
